var input=angular.module('input',[]);
input.directive('commonInput',function(){
    return{
        restrict:'A',
        link:function($scope,$element){
            $element.focus(function(){
               $element.prev().animate({
                   "top":"-15px"
               },'fast');
                $element.prev().css({
                    "color":"#c0c0c0",
                    "fontSize":"12px"
                });
            })
            $element.blur(function(){
               if($element.val().trim()==""){
                   $element.prev().animate({
                       "top":"7px"
                   },'fast');

                   $element.prev().css({
                       "color":"#595959",
                       "fontSize":"14px"
                   });
               }
            })

        }
    }
})

input.directive('commonDataTimePicker',function(){
    return{
        restrict:'A',
        link:function($scope,$element){
            $element.focus(function(){
                $element.prev().animate({
                    "top":"-15px"
                },'fast');
                $element.prev().css({
                    "color":"#c0c0c0",
                    "fontSize":"12px"
                });
            })
            $element.blur(function(){
                var flag=false;
                $("body").find(".datetimepicker").each(function(){
                     if($(this).is(':visible')){
                          flag=true;
                         return flag;
                     }
                })
                if(($element.val().trim()=="")&& (flag==false)){
                    $element.prev().animate({
                        "top":"7px"
                    },'fast');

                    $element.prev().css({
                        "color":"#595959",
                        "fontSize":"14px"
                    });
                }
            })
        }
    }
})

input.directive('commonInputUl',function(){
    return{
        restrict:'A',
        link:function($scope,$element){
            $element.focus(function(){
                $element.prev().animate({
                    "top":"-15px"
                },'fast');
                $element.prev().css({
                    "color":"#c0c0c0",
                    "fontSize":"12px"
                });
            })
            $element.blur(function(){
                if(($element.val().trim()=="")&& ($element.parent().find('ul').is(':hidden'))){
                    $element.prev().animate({
                        "top":"7px"
                    },'fast');

                    $element.prev().css({
                        "color":"#595959",
                        "fontSize":"14px"
                    });
                }
            })
        }
    }
})

/*在失焦后显示验证信息*/
input.directive('ngFocus', function () {
        var FOCUS_CLASS = "ng-focused";
        return{
            restrict:'A',
            require:'ngModel',
            link: function (scope, element, attrs,ctrl) {
                ctrl.$focused = false;
                element.bind('focus', function (evt) {
                    element.addClass(FOCUS_CLASS);
                    scope.$apply(function () {
                        ctrl.$focused = true;
                    });
                }).bind('blur', function () {
                        element.removeClass(FOCUS_CLASS);
                        scope.$apply(function(){
                            ctrl.$focused = false;
                        })
                    })
            }
        }
    })

/*确认密码校验一致性*/
input.directive('compare',function(){
    var o={};
    o.strict='AE';
    o.scope={
        orgText:'=compare'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.compare=function(v){
            if(v!=""){
                return v==sco.orgText;
            }else{
                return true
            }

        }
        sco.$watch('orgText',function(){
            con.$validate();
        })
    }
    return o;
})

/*确认密码校验一致性*/
input.directive('compareNull',function(){
    var o={};
    o.strict='AE';
    o.scope={
        orgText:'=compareNull'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.compareNull=function(v){
                return v==sco.orgText;
        }
        sco.$watch('orgText',function(){
            con.$validate();
        })
    }
    return o;
})

input.directive('compareagent',function(){
    var o={};
    o.strict='AE';
    o.scope={
        orgText:'=compareagent'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.compareagent=function(v){
           if(sco.orgText.type==2){
                if(v!=""&&v!=null){
                return v==sco.orgText.name;
                }else{
                return true
                }
           }else{
               return true
           }
        }
        sco.$watch('orgText',function(){
            con.$validate();
        },true)
    }
    return o;
})

input.directive('comparerate',function(){
    var o={};
    o.strict='AE';
    o.scope={
        orgText:'=comparerate'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.comparerate=function(v){
               var regu =/^\d+(\.\d+)?$/;
              var re = new RegExp(regu);
                if(v!=""&&v!=null&&re.test(v)){
                    return parseFloat(v)>=parseFloat(sco.orgText);
                }else{
                    return true
                }

        }
        sco.$watch('orgText',function(){
            con.$validate();
        },true)
    }
    return o;
})

input.directive('testcode',function(){
    var o={};
    o.strict='AE';
    o.scope={
        orgText:'=testcode'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.testcode=function(v){
                if(v!=""&&v!=null){
                    var re=/[\,\\\/\:\*\?\"\<\>\|]+/;
                    if (!re.test(v))
                    {
                        return false;
                    }
                }else{
                    return true
                }

        }
        sco.$watch('orgText',function(){
            con.$validate();
        },true)
    }
    return o;
})

/*验证身份证号*/
input.directive('idnumber', function(){
    return {
        require: 'ngModel',
        link: function (scope, ele, attrs, ctrl) {
            ctrl.$validators.idnumber = function (modelValue, viewValue) {
                if (modelValue) {
                    var idcard = modelValue;
                    var Errors = new Array("验证通过!", "身份证号码位数不对!", "身份证号码出生日期超出范围或含有非法字符!",
                        "身份证号码校验错误!", "身份证地区非法!");
                    var area = {11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林",
                        23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东",
                        41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川",
                        52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆",
                        71: "台湾", 81: "香港", 82: "澳门", 91: "国外"}
                    var Y, JYM;
                    var S, M;
                    var idcard_array = new Array();
                    idcard_array = idcard.split("");
                    //地区检验
                    if (area[parseInt(idcard.substr(0, 2))] == null) {
                        return false;
                    }
                    //身份号码位数及格式检验
                    switch (idcard.length) {
                        case 15:

                            if ((parseInt(idcard.substr(6, 2)) + 1900) % 400 == 0
                                || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 != 0 && (parseInt(idcard
                                .substr(6, 2)) + 1900) % 4 == 0)) {
                                ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/; //闰年出生日期的合法性正则表达式
                            } else {
                                ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/; //平年出生日期的合法性正则表达式
                            }
                            if (ereg.test(idcard)) {
                                return true;
                            } else
                            return false;
                        case 18:
                            if (parseInt(idcard.substr(6, 4)) % 400 == 0
                                || (parseInt(idcard.substr(6, 4)) % 100 != 0 && parseInt(idcard
                                .substr(6, 4)) % 4 == 0)) {
                                ereg = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;
                            } else {
                                ereg = /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;
                            }
                            if (ereg.test(idcard)) {
                                //计算校验位
                                S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7
                                    + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9
                                    + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10
                                    + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5
                                    + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8
                                    + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4
                                    + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2
                                    + parseInt(idcard_array[7]) * 1
                                    + parseInt(idcard_array[8]) * 6
                                    + parseInt(idcard_array[9]) * 3;
                                Y = S % 11;
                                M = "F";
                                JYM = "10X98765432";
                                M = JYM.substr(Y, 1);
                                if (M == idcard_array[17])//判断校验位
                                {
                                    return true;
                                } else {
                                    return false;
                                }
                            }
                            else
                            return false;
                        default:
                            return false;
                    }
                };
                return true;
            }
        }
    }
})

/*验证银行卡号*/
input.directive('banknum', function(){
    return {
        require: 'ngModel',
        link: function (scope, ele, attrs, ctrl) {
            ctrl.$validators.banknum = function (modelValue, viewValue) {
                if (modelValue) {
                    var  bankno= modelValue;
                    var lastNum = bankno.substr(bankno.length - 1, 1);// 取出最后一位（与luhm进行比较）
                    var first15Num = bankno.substr(0, bankno.length - 1);// 前15或18位
                    var newArr = new Array();
                    for (var i = first15Num.length - 1; i > -1; i--) {    // 前15或18位倒序存进数组
                        newArr.push(first15Num.substr(i, 1));
                    }
                    var arrJiShu = new Array();  // 奇数位*2的积 <9
                    var arrJiShu2 = new Array(); // 奇数位*2的积 >9
                    var arrOuShu = new Array();  // 偶数位数组
                    for (var j = 0; j < newArr.length; j++) {
                        if ((j + 1) % 2 == 1) {// 奇数位
                            if (parseInt(newArr[j]) * 2 < 9)
                                arrJiShu.push(parseInt(newArr[j]) * 2);
                            else
                                arrJiShu2.push(parseInt(newArr[j]) * 2);
                        }
                        else // 偶数位
                            arrOuShu.push(newArr[j]);
                    }
                    var jishu_child1 = new Array();// 奇数位*2 >9 的分割之后的数组个位数
                    var jishu_child2 = new Array();// 奇数位*2 >9 的分割之后的数组十位数
                    for (var h = 0; h < arrJiShu2.length; h++) {
                        jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
                        jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
                    }
                    var sumJiShu = 0; // 奇数位*2 < 9 的数组之和
                    var sumOuShu = 0; // 偶数位数组之和
                    var sumJiShuChild1 = 0; // 奇数位*2 >9 的分割之后的数组个位数之和
                    var sumJiShuChild2 = 0; // 奇数位*2 >9 的分割之后的数组十位数之和
                    var sumTotal = 0;
                    for (var m = 0; m < arrJiShu.length; m++) {
                        sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
                    }
                    for (var n = 0; n < arrOuShu.length; n++) {
                        sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
                    }
                    for (var p = 0; p < jishu_child1.length; p++) {
                        sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
                        sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
                    }
                    // 计算总和
                    sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

                    // 计算Luhm值
                    var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
                    var luhm = 10 - k;
                    if (lastNum == luhm) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return true;
            }
        }
    }
})




/*显示隐藏底部二维码*/
input.directive('mouseOverLeave', function(){
    return {
        restrict: 'A',
        scope: {
            hover: "="
        },
        link: function(scope, elem, attr){
            elem.bind('mouseover', function(){
                $(".wx-code").fadeIn();
            });
            elem.bind('mouseleave', function(){
                $(".wx-code").fadeOut();
            });
        }
    }
});

/*按钮重复点击*/
input.directive('clickAndDisable', function() {
    return {
        scope: {
            clickAndDisable: '&'
        },
        link: function(scope, iElement, iAttrs) {
            iElement.bind('click', function() {
                iElement.prop('disabled',true);
                scope.clickAndDisable().finally(function() {
                    iElement.prop('disabled',false);
                })
            });
        }
    };
})

/*验证金额小于全部金额*/
input.directive('comparemoney',function(){
    var o={};
    o.strict='AE';
    o.scope={
        orgText:'=comparemoney'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.comparemoney=function(v){

            v=parseFloat(v);
            var text= parseFloat(sco.orgText)
            return v<=text;
        }
        sco.$watch('orgText',function(){
            con.$validate();
        })
    }
    return o;
})

/*图片查看器*/
input.directive('ngImgMax',function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs){
            $(element).viewer({
                navbar: false
            });
        }
    }
})


/*终端数量大于3，pos申请书必填*/
input.directive('checkposimg',function(){
    var o={};
    o.strict='AE';
    o.scope={
        orgText:'=checkposimg'
    }
    o.require='ngModel';
    o.link=function(sco,ele,att,con){
        con.$validators.checkposimg=function(v){
            if(sco.orgText>3){
                if(v==""||v==undefined||v==null){
                    return false;
                }
            }
                return true;
        }
        sco.$watch('orgText',function(){
            con.$validate();
        })
    }
    return o;
})

/*模糊查询模板*/
input.directive('fuzzyModel',function(){
     return{
         restrict : 'EA',
         transclude : true,
        // replace : true,
         scope : {
             fuzzyId : '=fuzzyId',
             fuzzyName : '=fuzzyName',
             fuzzyList : '=fuzzyList',
             fuzzyLabel:'=fuzzyLabel'
         },
         template:'<input type="hidden" ng-model="fuzzyId"/><label class="common-label fuzzy_label">{{fuzzyLabel}}</label>'+
             '<input class="form-control common-input" ng-focus="searchList()" autocomplete="off" ng-change="changeName()"   ng-keyup="searchList()" common-input-ul  type="text" ng-model="fuzzyName"/>'+
             '<ul class="bank-select-ul" ng-show="selectContent">'+
                '<li ng-repeat="item in fuzzyList" ng-click="selectItem(item.id,item.name,$event)">{{item.name}}</li>'+
             '</ul>',
         link : function(scope, element, attrs) {
             scope.selectContent=false;
            /* setTimeout(function(){
                 scope.fuzzyAllList=scope.fuzzyList;
             },2000)*/
             setTimeout(function(){
                 scope.fuzzyAllList=scope.fuzzyList;
                 if(scope.fuzzyId!=null&&scope.fuzzyId!=""){
                     for(var index in scope.fuzzyAllList){
                         if(scope.fuzzyAllList[index].id==scope.fuzzyId){
                             scope.fuzzyName=scope.fuzzyAllList[index].name;
                             break;
                         }
                     }
                     $(".fuzzy_label").css({
                         "top": -15+"px",
                         "color":"rgb(192, 192, 192)",
                         "fontSize": 12+"px"
                     });
                 }
             },2000)


             scope.searchList=function(){
                 scope.selectContent=true;
               //  scope.fuzzyAllList=scope.fuzzyList;
                 var bankAll=scope.fuzzyList;
                 var newBankList=[];
                 if(scope.fuzzyName!=undefined){
                     for(var index in bankAll){
                         var str=bankAll[index].name;
                         if(str.indexOf(scope.fuzzyName)!=-1){
                             newBankList.push(bankAll[index]);
                         }
                     }
                     scope.fuzzyList=newBankList;
                 }else{
                     scope.fuzzyList=bankAll;
                 }
             }
             /*点击li将选择的li放入input框中*/
             scope.selectItem=function(id,name,$event){
                 scope.fuzzyName=name;
                 scope.fuzzyId=id;
                 scope.selectContent=false;
                 $($event.target).parent().parent().find('label').css({
                     "top": -15+"px",
                     "color":"rgb(192, 192, 192)",
                     "fontSize": 12+"px"
                 });
             }
             /*input为空时，显示全部列表*/
             scope.changeName=function(){
                 if(scope.fuzzyName==""||scope.fuzzyName==null){
                     scope.fuzzyList=scope.fuzzyAllList;
                 }
             }

         }
    }
})
 //返回顶部
input.directive('backToTop',function(){
    return {
        restrict: "E",
        link: function (scope, element, attr) {
            var e = $(element);
            $(window).scroll(function () {                 //滚动时触发
                if ($(document).scrollTop() > 300)         //获取滚动条到顶部的垂直高度,到相对顶部300px高度显示
                    e.addClass("showme") ;
                else
                    e.removeClass("showme");
            });
            /*点击回到顶部*/
            e.click(function () {
                $('html,body').animate({                 //添加animate动画效果
                    scrollTop: 0
                }, 500);
            });
        }
    };
})

//导出数据
input.directive('export',function($rootScope,$http,$location){
    return {
        restrict:'E',
        template:'<button type="button" class="btn common-btn-white pull-right" ng-disabled="downloadDisabled" ng-click="exportSubAgent()">{{downloadText}}</button>',
        scope : {
            data : '='
        },
        link:function(scope,element,attrs){
//            console.log(scope.data);
//            console.log($rootScope.basePath);
            scope.downloadText="导出数据";
            scope.downloadDisabled=false;
            scope.exportSubAgent = function () {
                scope.downloadDisabled=true;
                scope.downloadText="导出中";
                $http({
                    method:"POST",
                    dataType:"json",
                    url:$rootScope.basePath+scope.data.src,
                    data: $.param(scope.data.data),
                    headers:{
                        'Content-Type':'application/x-www-form-urlencoded'
                    },
                    timeout: 10000
                })
                    .success(function(data){
                        if(data.respCode=="failure_session"){
                            //登录超时
                            $location.path('/index');

                        }else{
                            scope.downloadDisabled=false;
                            scope.downloadText="导出数据";
                            if(data.respCode=="success"){
                                scope.data.tipConf.showTipContent=true;
                                scope.data.tipConf.src="image/yes.png" ;
                                scope.data.tipConf.title="账单已加入下载列表" ;
                                scope.data.tipConf.subtitle="请点击下载管理中心按钮查看" ;
                            }else{
                                scope.data.tipConf.showTipContent=true;
                                scope.data.tipConf.src="image/no.png" ;
                                scope.data.tipConf.title=data.respMsg ;
                                scope.data.tipConf.subtitle="" ;
                                scope.downloadText="导出数据";
                                scope.downloadDisabled=false;
                            }
                        }
                    })
                    .error(function(){
                        scope.data.tipConf.showTipContent=true;
                        scope.data.tipConf.src="image/no.png" ;
                        scope.data.tipConf.title="系统繁忙，请稍后重试" ;
                        scope.data.tipConf.subtitle="" ;
                        scope.downloadText="导出数据";
                        scope.downloadDisabled=false;
                    })
            }
        }
    }
})

//重置按钮
input.directive('reset',function($rootScope){
    var dataObj;
    return {
        restrict:'E',
        template:'<button type="button" class="btn common-btn-white  center-block" ng-click="resetClick()">重置</button>',
        scope : {
            data : '='
        },
        link:function(scope,element,attrs){
            dataObj=attrs.original;
            dataObj=$.parseJSON(dataObj);
             scope.resetClick=function(){
                 for(var j in scope.data){
                      scope.data[j]='';
                      for(var k in dataObj){
                         if(k==j){
                             scope.data[j]= dataObj[k];
                             break;
                         }else{
                             scope.data[j]='';
                         }
                     }
                 }
                 $(".auth_form .common-label").not(".time-label").css({
                     "color":"#595959",
                     "fontSize":"14px",
                     "top":"7px"
                 });
             }
        }
    }
})
//查询按钮
input.directive('searchBtn',function(){
    return{
        restrict:'A',
        link:function(scope,element,attrs){
            element.bind('click',function(){
                if (scope.paginationConf.currentPage == 1) {
                    scope.getAllEmployee();
                } else {
                    scope.paginationConf.currentPage = 1
                }
            })
        }
    }
})

/*九盈input框*/
input.directive('joinCommonInput',function(){
    return{
        restrict:'A',
        link:function($scope,$element){
            $element.focus(function(){
                $element.prev().animate({
                    "bottom":"0px"
                });
                $element.prev().css({
                    "color":"#2e3a4b"
                });
            })
            $element.blur(function(){
                if($element.val().trim()==""){
                    $element.prev().animate({
                        "bottom":"-19px"
                    });
                    $element.prev().css({
                        "color":"#9b9b9b"
                    });
                }
            })

        }
    }
})
